﻿Imports System.Net
Imports System.Threading
Imports System.Windows

Namespace TweeVo
	Public NotInheritable Class TiVoPoller
		Private Shared _timer As Timer
		Private Shared _polling As Boolean

		Private Sub New()
		End Sub
		Public Shared Sub Start()
			Logger.Log("Starting TiVoPoller", LoggerSeverity.Info)

			If _timer Is Nothing Then
				_timer = New Timer(AddressOf PollTiVo)
			End If

			' poll every 15 minutes
			_timer.Change(0, 15*60*1000)
		End Sub

		Public Shared Sub [Stop]()
			If _timer IsNot Nothing Then
				_timer.Change(Timeout.Infinite, Timeout.Infinite)
			End If
		End Sub

		Private Shared Sub PollTiVo(ByVal state As Object)
			Dim tries As Integer = 0
			Dim success As Boolean = False

			Logger.Log("PollTiVo Now: " & Date.Now, LoggerSeverity.Info)
			If _polling Then
				Return
			End If

			_polling = True

			For Each t As TiVo In TweeVoSettings.Default.TiVos.Values
				If t.Active Then
					' try to poll 3 times
					Do While tries < 3 AndAlso Not success
						Try
							Dim list As List(Of NPLEntry) = t.GetNowPlayingList()
							If list IsNot Nothing Then
								For Each nplEntry As NPLEntry In list
									' if the entry is valid, tweet it
									If ((Not nplEntry.Suggestion) OrElse (nplEntry.Suggestion AndAlso TweeVoSettings.Default.Suggestions <> SuggestionsType.NoShow)) AndAlso nplEntry.CaptureDate > t.LastPolled Then
										Dim tweet As String = CreateTwitterString(t.Machine, nplEntry)
										Twitter.PostTwitterUpdate(tweet)
									End If
								Next nplEntry
							End If
							success = True
							t.LastPolled = Date.Now
							Logger.Log("Completed processing " & t.Machine, LoggerSeverity.Info)
						Catch ex As Exception
							Logger.Log("Exception on " & t.Machine & " with ex: " & ex.ToString(), LoggerSeverity.Error)
							success = False
							tries += 1

							' if we've failed 3 times, notify somebody
							If tries = 3 Then
								Logger.Log("3 retries on " & t.Machine & " with ex: " & ex.ToString(), LoggerSeverity.Error)
								TryCast(Application.Current, App).ShowBalloonTip("Error with " & t.Machine & ": " & ex.Message & "  If this keeps happening, you may want to disable TweeVo from communicating with this TiVo.")
							End If
						End Try
					Loop
					tries = 0
				End If
				success = False
			Next t
			_polling = False
			TweeVoSettings.Default.Save()
		End Sub

		Private Shared Function GetShortUrl(ByVal url As String) As String
			' get a shortened URL using tinyurl.com
			Return New WebClient().DownloadString("http://tinyurl.com/api-create.php?url=" & url)
		End Function

		Private Shared Function CreateTwitterString(ByVal tivoName As String, ByVal nplEntry As NPLEntry) As String
			' this url will take you to the specific episode page...the "x" can be anything.
			Dim progId As String = nplEntry.ProgramID.Substring(0, 2) + New String("0"c, 14 - nplEntry.ProgramID.Length) & nplEntry.ProgramID.Substring(2)
			Dim url As String = "http://tvlistings.zap2it.com/tv/x/" & progId
			Dim tinyUrl As String = GetShortUrl(url)

			Dim tweet As String

			Dim prefix As String = String.Empty

			Select Case TweeVoSettings.Default.TwitterPrefix
				Case PrefixType.Name
					prefix &= tivoName & "> "
				Case PrefixType.TiVo
					prefix &= "TiVo> "
				Case PrefixType.Nothing
					' nuttin'
			End Select

			If nplEntry.Suggestion AndAlso TweeVoSettings.Default.Suggestions = SuggestionsType.ShowWithPrefix Then
				prefix &= "(S) "
			End If

			If String.IsNullOrEmpty(nplEntry.EpisodeTitle) Then
				tweet = String.Format("{0}{1} at {2} on {3} {4} ", prefix, nplEntry.Title, nplEntry.CaptureDate.ToShortTimeString(), nplEntry.SourceChannel, nplEntry.SourceStation)

			Else
				tweet = String.Format("{0}{1}: ""{2}"" at {3} on {4} {5} ", prefix, nplEntry.Title, nplEntry.EpisodeTitle, nplEntry.CaptureDate.ToShortTimeString(), nplEntry.SourceChannel, nplEntry.SourceStation)
			End If

			Dim extra As Integer = (tweet.Length + tinyUrl.Length) - 140
			If extra > 0 Then
				tweet = tweet.Substring(0, tweet.Length-extra-4) & "... "
			End If

			Return HttpUtility.UrlEncode(tweet) & tinyUrl
		End Function
	End Class
End Namespace